package com.atguigu.day02;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock方式 多线程
 *
 * @author sx
 * @date 2022-02-18 10:34
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        //并发：多线程操作同一个资源类，把资源类丢入线程
        Ticket2 ticket = new Ticket2();

        //lambda表达式
        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 30; i++) {
                ticket.sale();
            }
        }, "C").start();

    }
}

//资源类 OOP

/**
 * lock三步走
 * 1、创建锁：new ReentrantLock()
 * 2、加锁：lock.lock();
 * 3、解锁：lock.unlock();
 */
class Ticket2 {
    //属性、方法
    private int number = 30;

    Lock lock = new ReentrantLock();

    //卖票方法
    public void sale() {
        //加锁
        lock.lock();

        try {
            //业务代码
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (30 - (--number)) + "张票，剩余：" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }
    }
}
